<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>WebSocket测试页面 - 商户统计数据</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
            line-height: 1.6;
        }
        .container {
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            border: 1px solid #ddd;
            border-radius: 5px;
        }
        h1 {
            color: #333;
        }
        .status {
            padding: 10px;
            margin: 10px 0;
            border-radius: 5px;
        }
        .connected {
            background-color: #d4edda;
            color: #155724;
        }
        .disconnected {
            background-color: #f8d7da;
            color: #721c24;
        }
        pre {
            background-color: #f5f5f5;
            padding: 10px;
            border-radius: 5px;
            overflow: auto;
        }
        button {
            padding: 8px 16px;
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            margin-right: 10px;
            margin-bottom: 5px;
        }
        button:hover {
            background-color: #0069d9;
        }
        .card {
            border: 1px solid #ddd;
            border-radius: 5px;
            padding: 15px;
            margin-bottom: 15px;
        }
        table {
            width: 100%;
            border-collapse: collapse;
        }
        table, th, td {
            border: 1px solid #ddd;
        }
        th, td {
            padding: 8px;
            text-align: left;
        }
        th {
            background-color: #f2f2f2;
        }
        .log {
            height: 150px;
            overflow-y: auto;
            font-family: monospace;
            font-size: 12px;
            margin-top: 10px;
        }
        .log-entry {
            margin: 2px 0;
            padding: 2px 5px;
            border-bottom: 1px solid #eee;
        }
        .log-info {
            color: #0c5460;
        }
        .log-error {
            color: #721c24;
        }
        .log-success {
            color: #155724;
        }
        .api-buttons {
            margin-top: 10px;
            display: flex;
            flex-wrap: wrap;
            gap: 5px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>WebSocket测试页面 - 商户统计数据</h1>
        
        <div id="connectionStatus" class="status disconnected">
            状态: 未连接
        </div>
        
        <div>
            <button id="connectBtn">连接</button>
            <button id="disconnectBtn" disabled>断开连接</button>
        </div>
        
        <div class="card">
            <h2>连接信息</h2>
            <p>WebSocket端点: <code id="wsEndpoint"></code></p>
            <p>订阅主题: <code>/topic/stats</code></p>
        </div>
        
        <div class="card">
            <h2>API测试</h2>
            <p>使用以下按钮测试WebSocket消息发送:</p>
            <div class="api-buttons">
                <button id="sendBtn">发送实际数据</button>
                <button id="sendMockBtn">发送模拟数据</button>
                <button id="sendTextBtn">发送文本消息</button>
            </div>
        </div>
        
        <div class="card">
            <h2>订单总览</h2>
            <div id="statsOverview">
                <p>总订单数: <span id="totalOrders">-</span></p>
                <p>总收入: <span id="totalRevenue">-</span> 元</p>
                <p>最后更新: <span id="lastUpdate">-</span></p>
            </div>
        </div>
        
        <div class="card">
            <h2>分类统计</h2>
            <table id="categoryTable">
                <thead>
                    <tr>
                        <th>服务类型</th>
                        <th>订单数</th>
                        <th>收入(元)</th>
                    </tr>
                </thead>
                <tbody id="categoryStats">
                    <!-- 动态填充 -->
                    <tr><td colspan="3">暂无数据</td></tr>
                </tbody>
            </table>
        </div>
        
        <div class="card">
            <h2>收入排行榜</h2>
            <ol id="leaderboard">
                <!-- 动态填充 -->
                <li>暂无数据</li>
            </ol>
        </div>
        
        <div class="card">
            <h2>原始消息</h2>
            <pre id="rawMessage">无消息</pre>
        </div>
        
        <div class="card">
            <h2>日志</h2>
            <div id="log" class="log"></div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/sockjs-client@1.5.1/dist/sockjs.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/stomp-websocket@2.3.4-next/lib/stomp.min.js"></script>
    <script>
        // 获取当前主机和端口
        const host = window.location.host;
        const wsEndpoint = `http://${host}/ws`;
        document.getElementById('wsEndpoint').textContent = wsEndpoint;
        
        let stompClient = null;
        let messageCount = 0;
        
        // 日志函数
        function log(message, type = 'info') {
            const logDiv = document.getElementById('log');
            const entry = document.createElement('div');
            entry.className = `log-entry log-${type}`;
            entry.textContent = `[${new Date().toLocaleTimeString()}] ${message}`;
            logDiv.insertBefore(entry, logDiv.firstChild);
            
            // 限制日志条数
            if (logDiv.children.length > 50) {
                logDiv.removeChild(logDiv.lastChild);
            }
            
            console.log(`[${type}] ${message}`);
        }
        
        function connect() {
            try {
                log('开始连接WebSocket...');
                
                const socket = new SockJS('/ws');
                stompClient = Stomp.over(socket);
                
                // 禁用STOMP调试日志
                stompClient.debug = null;
                
                stompClient.connect({}, function(frame) {
                    // 连接成功
                    const statusDiv = document.getElementById('connectionStatus');
                    statusDiv.textContent = '状态: 已连接';
                    statusDiv.className = 'status connected';
                    
                    document.getElementById('connectBtn').disabled = true;
                    document.getElementById('disconnectBtn').disabled = false;
                    
                    log(`连接成功: ${frame}`, 'success');
                    
                    // 订阅主题
                    stompClient.subscribe('/topic/stats', function(message) {
                        messageCount++;
                        log(`收到消息 #${messageCount}`);
                        handleMessage(message.body);
                    });
                    
                }, function(error) {
                    // 连接错误
                    log(`连接错误: ${error}`, 'error');
                    const statusDiv = document.getElementById('connectionStatus');
                    statusDiv.textContent = '状态: 连接失败';
                    statusDiv.className = 'status disconnected';
                });
            } catch (e) {
                log(`连接异常: ${e.message}`, 'error');
            }
        }
        
        function disconnect() {
            if (stompClient !== null) {
                try {
                    stompClient.disconnect(function() {
                        log('已断开连接');
                    });
                } catch (e) {
                    log(`断开连接异常: ${e.message}`, 'error');
                } finally {
                    stompClient = null;
                    
                    const statusDiv = document.getElementById('connectionStatus');
                    statusDiv.textContent = '状态: 已断开连接';
                    statusDiv.className = 'status disconnected';
                    
                    document.getElementById('connectBtn').disabled = false;
                    document.getElementById('disconnectBtn').disabled = true;
                }
            }
        }
        
        function handleMessage(messageBody) {
            // 显示原始消息
            document.getElementById('rawMessage').textContent = messageBody;
            document.getElementById('lastUpdate').textContent = new Date().toLocaleString();
            
            try {
                // 检查是否是简单字符串消息
                if (messageBody.startsWith('"') && messageBody.endsWith('"')) {
                    const textMessage = JSON.parse(messageBody);
                    log(`接收到文本消息: ${textMessage}`, 'success');
                    return;
                }
                
                const data = JSON.parse(messageBody);
                
                // 更新总览数据
                document.getElementById('totalOrders').textContent = data.totalOrders;
                document.getElementById('totalRevenue').textContent = (data.totalRevenue / 100).toFixed(2); // 分转元
                
                // 更新分类统计
                const categoryStats = document.getElementById('categoryStats');
                categoryStats.innerHTML = '';
                
                if (data.categoryStats && data.categoryStats.length > 0) {
                    data.categoryStats.forEach(category => {
                        const row = document.createElement('tr');
                        row.innerHTML = `
                            <td>${category.type}</td>
                            <td>${category.orders}</td>
                            <td>${(category.revenue / 100).toFixed(2)}</td>
                        `;
                        categoryStats.appendChild(row);
                    });
                } else {
                    categoryStats.innerHTML = '<tr><td colspan="3">暂无数据</td></tr>';
                }
                
                // 更新排行榜
                const leaderboard = document.getElementById('leaderboard');
                leaderboard.innerHTML = '';
                
                if (data.leaderboard && data.leaderboard.length > 0) {
                    data.leaderboard.forEach(item => {
                        const li = document.createElement('li');
                        li.textContent = item;
                        leaderboard.appendChild(li);
                    });
                } else {
                    leaderboard.innerHTML = '<li>暂无数据</li>';
                }
                
                log('数据更新成功', 'success');
            } catch (e) {
                log(`解析消息失败: ${e.message}`, 'error');
            }
        }
        
        // API调用函数
        function callApi(endpoint) {
            log(`调用API: ${endpoint}`);
            fetch(endpoint)
                .then(response => response.json())
                .then(data => {
                    log(`API响应: ${JSON.stringify(data).substring(0, 100)}...`, 'success');
                })
                .catch(error => {
                    log(`API错误: ${error.message}`, 'error');
                });
        }
        
        // 事件监听
        document.getElementById('connectBtn').addEventListener('click', connect);
        document.getElementById('disconnectBtn').addEventListener('click', disconnect);
        document.getElementById('sendBtn').addEventListener('click', () => callApi('/websocket/send'));
        document.getElementById('sendMockBtn').addEventListener('click', () => callApi('/websocket/send-mock'));
        document.getElementById('sendTextBtn').addEventListener('click', () => callApi('/websocket/send-text'));
        
        // 页面加载完成后自动连接
        window.addEventListener('load', function() {
            log('页面加载完成，准备连接...');
            setTimeout(connect, 1000); // 延迟1秒连接
        });
    </script>
</body>
</html> 